package com.jd.tuning.jvm.objectpool.datasource;

import lombok.Data;
import org.apache.commons.pool2.impl.GenericObjectPool;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;


/**
 * 数据源
 *
 * 现有问题
 * 1、互相引用，不太优雅
 * 2、有很多方法没有实现
 *
 *
 */
@Data
public class CoolDataSource implements DataSource {

    private GenericObjectPool<MyConnection> pool;

    public CoolDataSource(){
        //数据源，初始化连接池工厂
        //GenericObjectPool 引用了factory （互相引用）
        ConnectionPooledObjectFactory factory =new ConnectionPooledObjectFactory();
        this.pool=new GenericObjectPool<MyConnection>(factory);
        //factory 引用了pool 不太优雅（互相引用）
        factory.setPool(pool);
    }


    @Override
    public Connection getConnection() throws SQLException {
        try {
            return this.pool.borrowObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new SQLException("获取连接失败",e);
        }
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return this.getConnection();
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        throw new UnsupportedOperationException("不支持的操作");
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        throw new UnsupportedOperationException("不支持的操作");
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {
        throw new UnsupportedOperationException("不支持的操作");
    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {
        throw new UnsupportedOperationException("不支持的操作");
    }

    @Override
    public int getLoginTimeout() throws SQLException {
        throw new UnsupportedOperationException("不支持的操作");
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        throw new UnsupportedOperationException("不支持的操作");
    }
}
